package com.fingard.dsp.bank.directbank.jstzrcb01;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextWriter;

/**
 * @author dicke
 * @date 2018/9/16 10:58
 */
public class JSTZRCB01Base extends DirectBase implements ITcpClient{
    /**同行1*/
    String sameBank = "1";
    /**跨行0*/
    String notSameBank = "0";
    /**对私*/
    String isPrivate = "1";

    String BANK_RET_RIGHT_CODE = "000000";

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    protected void writeCommonHead(XmlTextWriter xmlWriter, JSTZRCB01Header header){
        xmlWriter.writeStartDocument();
        xmlWriter.directWrite("<?xml version=\"1.0\" encoding=\"GBK\" ?>");
        xmlWriter.writeStartElement("Message");
        xmlWriter.writeStartElement("Head");
        xmlWriter.writeElementString("TrsCode", header.transCode);
        if (header.reqDateTime == null) {
            header.reqDateTime = new Date();
        }
        //交易日期
        xmlWriter.writeElementString("ERPTrsTimestamp", Format.DateTimeFormat.format(header.reqDateTime));
        if(!StringHelper.isNullOrEmpty(header.transCode) && !"B2EActBalQry".equals(header.transCode)) {
            if(!"B2EBatchTrsResQry".equals(header.transCode)) {
                String ERPJnlNo =  String.format("%016d",header.reqSeqNo);
                xmlWriter.writeElementString("ERPJnlNo",ERPJnlNo);
            }
        }
        xmlWriter.writeEndElement();

    }

    protected String[] sendToBank(String pReqStr,String opName) throws Exception{
        WriteBankLogStep2(pReqStr);
        String[] retStr = new String[]{"",""};
        String tmpAddrUrl = "http://" + bankFront.serverIP + ":" + bankFront.serverPort+"/eweb/" + opName + ".do?usrID="+
                bankFront.userName+"&userPassword=" + bankFront.loginPasswd + "&operatorID="+bankFront.operator+"&SIGDATA=1";
        String sendInfo = pReqStr;
        WriteBankLogLn("2.提交银行的地址：" + tmpAddrUrl);
        WebRequest tmpWebRequest = new WebRequest(tmpAddrUrl);
        tmpWebRequest.setConnectTimeout(10000);
        tmpWebRequest.setRequestProperty("User-Agent", "API");

        byte[] tmpUpBytes = sendInfo.getBytes(getCharset());
        retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());

        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {

    }
}
